import tablib
from import_export import resources
from accounts.models import *
from import_export.fields import Field


# 学生信息导出


class InfoResource(resources.ModelResource):
    # 导出显示文字
    name = Field(attribute='name', column_name=Info.name.field.verbose_name)
    sex = Field(attribute='sex', column_name=Info.sex.field.verbose_name)
    age = Field(attribute='age', column_name=Info.age.field.verbose_name)
    number = Field(attribute='number', column_name=Info.number.field.verbose_name)
    credit = Field(attribute='credit', column_name=Info.credit.field.verbose_name)
    dept = Field(attribute='Dept', column_name=Info.dept.field.verbose_name)

    def __init__(self, input_contract=None):
        super(InfoResource, self).__init__()
        field_list = Info._meta.fields
        self.verbose_name_dict = {}
        for i in field_list:
            self.verbose_name_dict[i.name] = i.verbose_name

    # 默认导入导出field的column_name为字段的名称，这里修改为字段的verbose_name
    def get_export_fields(self):
        fields = self.get_fields()
        for field in fields:
            field_name = self.get_field_name(field)
            # 如果有设置 verbose_name，则将 column_name 替换为 verbose_name, 否则维持原有的字段名。
            if field_name in self.verbose_name_dict.keys():
                field.column_name = self.verbose_name_dict[field_name]
        return fields

    def export(self, queryset=None, *args, **kwargs):

        # choices字段显示文字

        self.before_export(queryset, *args, **kwargs)

        if queryset is None:
            queryset = self.get_queryset()
        headers = self.get_export_headers()
        data = tablib.Dataset(headers=headers)

        for obj in self.iter_queryset(queryset):
            # 个性化显示 choice 的值
            # obj.gender = gender_choice[obj.gender]
            obj.sex = obj.get_sex_display()
            data.append(self.export_resource(obj))

        self.after_export(queryset, data, *args, **kwargs)

        return data

    class Meta:
        model = Info
        fields = '__all__'
        exclude = ['id']
        import_id_fields = ['name']
